package com.daoshu.mti.kafkaclient.handle;

import com.alibaba.fastjson.JSON;
import com.daoshu.mti.kafkaclient.bean.*;
import com.daoshu.mti.kafkaclient.constant.Topic;
import com.daoshu.mti.kafkaclient.consumer.TKmLgzsBaseConsumer;
import com.daoshu.mti.kafkaclient.service.*;
import com.daoshu.mti.kafkaclient.utils.AddressOrLngLatConvertUtil;
import com.daoshu.mti.kafkaclient.utils.ZdryYjUtilBean;
import com.daoshu.mti.kafkaclient.websocket.SocketType;
import com.daoshu.mti.kafkaclient.websocket.WebSocketUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Classname TKmTldpHandle
 * @Description TODO
 * @Date 2020/1/17 21:15
 * @Created by duchaof
 * @Version 1.0
 */
@Slf4j
@Component
public class TKmLgzsHandle extends TKmLgzsBaseConsumer {
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private TKmLgzsService tKmLgzsService;

    @Autowired
    private TKmZdryYjService tKmZdryYjService;

    @Autowired
    private WebSocketUtils webSocketUtils;
    @Autowired
    private AddressOrLngLatConvertUtil addressOrLngLatConvertUtil;

    @Autowired
    private TKmJurisdictionService tKmJurisdictionService;
    @Autowired
    private TKmLgService tKmLgService;
    @Autowired
    private TKmLgDiztService tKmLgDiztService;
    @Autowired
    private AddressOrLngLatConvertUtil addressUtil;

    private static Lock lock = new ReentrantLock();

    @Override
    @Transactional(rollbackFor = Exception.class)
    protected void onDealMessage(String message) {
        try {
            log.info("接收到topic：" + Topic.LGZS + "的消息" + ",线程：" + Thread.currentThread().getName() + "在" + sdf.format(new Date()) + "开始处理接受到的消息：" + message);
            TKmLgzsEntity kmLgzsEntity = JSON.parseObject(message, TKmLgzsEntity.class);
            TKmLgEntity lg = null;
            Integer res = null;
            lock.lock();
            try {
                // 根据省份证号 和 预警时间判断是否重复
                Boolean repeatFlag = tKmLgService.judgeRepeatData(kmLgzsEntity);
                if (repeatFlag) return;
                if (null != kmLgzsEntity.getLvguandaima() && kmLgzsEntity.getLvguandaima().length() > 0) {
                    lg = tKmLgService.getTkmlgByCode(kmLgzsEntity.getLvguandaima());
                }
                if (null == kmLgzsEntity.getLgmc() || null == kmLgzsEntity.getLgjd() || null == kmLgzsEntity.getLgwd()
                        || kmLgzsEntity.getLgmc().length() <= 0 || kmLgzsEntity.getLgwd().length() <= 0 || kmLgzsEntity.getLgjd().length() <= 0) {
                    if (null != lg) {
                        if (null != lg.getLgMc() && lg.getLgMc().length() > 0) kmLgzsEntity.setLgmc(lg.getLgMc());
                        if (null != lg.getLng() && lg.getLng().length() > 0) kmLgzsEntity.setLgjd(lg.getLng());
                        if (null != lg.getLat() && lg.getLat().length() > 0) kmLgzsEntity.setLgwd(lg.getLat());
                    }
                }
                res = tKmLgzsService.insert(kmLgzsEntity);
            } catch (Exception e) {
                log.error("插入旅馆住宿预警数据时发生异常：============》{}", e.getMessage());
            } finally {
                lock.unlock();
            }
            if (res > 0) {
                //log.info("数据插入成功，插入成功的数据为：" + message);
                TKmZdryYjEntity tKmZdryYjEntity = kmLgzsEntity.transtoZdryYjEntity();
                // 通过旅馆代码查询旅馆的相关信息
                //tKmZdryYjEntity.setCurrentJur(addressOrLngLatConvertUtil.checkAddress(kmLgzsEntity.getLgjd(),kmLgzsEntity.getLgwd()));
                if (null != lg && lg.getLgXzqhmc().length() > 0) {
                    tKmZdryYjEntity.setCurrentJur(lg.getLgXzqhmc());
                } else {
                    tKmZdryYjEntity.setCurrentJur(addressOrLngLatConvertUtil.checkAddress(kmLgzsEntity.getLgjd(), kmLgzsEntity.getLgwd()));
                }

                // 先从旅馆字典表中查询派出所和所属分局
                TKmLgDiztEntity tKmLgDiztEntity = tKmLgDiztService.getLgDictInfoByLgDm(kmLgzsEntity.getLvguandaima());
                if (null != tKmLgDiztEntity) {
                    if (null != tKmLgDiztEntity.getStationid())
                        tKmZdryYjEntity.setYjdPcsCode(tKmLgDiztEntity.getStationid());
                    if (null != tKmLgDiztEntity.getStation()) tKmZdryYjEntity.setYjdPcs(tKmLgDiztEntity.getStation());
                    if (null != tKmLgDiztEntity.getCountyseat())
                        tKmZdryYjEntity.setYjdSsfj(tKmLgDiztEntity.getCountyseat());
                }
                if (null == tKmZdryYjEntity.getX() || tKmZdryYjEntity.getY() == null || tKmZdryYjEntity.getX().length() <= 0 ||
                        tKmZdryYjEntity.getY().length() <= 0) {
                    StringBuilder sb = new StringBuilder();
                    if (tKmZdryYjEntity.getCurrentJur() != null) sb.append(tKmZdryYjEntity.getCurrentJur());
                    if (tKmZdryYjEntity.getServiceName() != null) sb.append(tKmZdryYjEntity.getServiceName());
                    Map<String, String> sendAddress = addressUtil.checkXY(sb.toString());
                    if (null != sendAddress) {
                        if (tKmZdryYjEntity.getX() == null || tKmZdryYjEntity.getX().length() <= 0)
                            tKmZdryYjEntity.setX(sendAddress.get("lng"));
                        if (tKmZdryYjEntity.getY() == null || tKmZdryYjEntity.getY().length() <= 0)
                            tKmZdryYjEntity.setY(sendAddress.get("lat"));
                    }
                }
                // 查询预警发生地的派出所代码和名称
                TKmJurisdictionEntity tKmJurisdictionEntity = tKmJurisdictionService.queryYjdPcsByLngAndLat(tKmZdryYjEntity.getX(), tKmZdryYjEntity.getY());
                if (null != tKmJurisdictionEntity) {
                    if (null == tKmZdryYjEntity.getYjdPcs() || tKmZdryYjEntity.getYjdPcs().length() <= 0)
                        tKmZdryYjEntity.setYjdPcs(tKmJurisdictionEntity.getMc());
                    if (null == tKmZdryYjEntity.getYjdPcsCode() || tKmZdryYjEntity.getYjdPcsCode().length() <= 0)
                        tKmZdryYjEntity.setYjdPcsCode(String.format("%.0f", Double.parseDouble(tKmJurisdictionEntity.getDm())));
                    if (null == tKmZdryYjEntity.getYjdSsfj() || tKmZdryYjEntity.getYjdSsfj().length() <= 0)
                        tKmZdryYjEntity.setYjdSsfj(tKmJurisdictionEntity.getSsfj());
                }

                tKmZdryYjService.insert(tKmZdryYjEntity);
                ZdryYjUtilBean zdryYjUtilBean = kmLgzsEntity.transtoZdryYjUtilBean();
                zdryYjUtilBean.setYjwybs(tKmZdryYjEntity.getWybs());

                if (null != tKmJurisdictionEntity) {
                    StringBuilder sb = new StringBuilder("重点人员【");
                    sb.append(zdryYjUtilBean.getName()).append("】在").append(tKmJurisdictionEntity.getMc()).append("管辖范围内的")
                            .append(tKmZdryYjEntity.getYjdd()).append("住宿。");
                    zdryYjUtilBean.setYjMsg(sb.toString());
                }

                //根据身份证查询管控民警，所属派出所，警种信息，根据这些信息
                if (null != kmLgzsEntity.getSfzh()) {
                    //查询此条预警是否是灰名单 或者是 已稳控  如果是就不推送
                    TKmZdryYjEntity entity = tKmZdryYjService.authGkjbAndWkzt(kmLgzsEntity.getSfzh());
                    if (!ObjectUtils.isEmpty(entity)) {
                        return;
                    }
                    List<String> tokens = tKmZdryYjService.findWebsocketPsuhUserListBySfzh(kmLgzsEntity.getSfzh());
                    if (null != tokens) {
                        webSocketUtils.sendWebsockMessageToUser(tokens,
                                Arrays.asList("lgzs", JSON.toJSONString(zdryYjUtilBean)), SocketType.ZDRRYJXX.getCode());

                    }

                }
            } else {
                log.error("数据插入失败，插入失败的数据为：" + message);
            }

        } catch (Exception e) {
            log.error("插入数据库发生异常=====>{}", e.getMessage());
        }
    }
}
